<template>
  <div style="max-width:100%;">
    <a-button v-if="canFix" type="primary" @click="showAddForm">新增</a-button>
    <a-table
      :columns="columns"
      :pagination="pagination"
      :data-source="data"
      :row-key="record => record.id"
      @change="handleTableChange"
    >
      <span slot="action" slot-scope="text, record">
        <a @click="showEditForm(record)">编辑</a>
        <a-divider type="vertical" />
        <a-popconfirm title="确定要删除吗?" @confirm="() => onDelete(record)">
          <a>删除</a>
        </a-popconfirm>
      </span>
      <span slot="qualPath" slot-scope="text, record">
        <img v-for="(v, index) in getImgList(text)" :key="index" width="50" :src="imgBase + '/' + v" />
      </span>
      <!--      window._CONFIG['staticDomainURL']-->
    </a-table>

    <a-modal :visible="modalVisible" @ok="handleOk" @cancel="handleCancel" :title="isEdit ? '编辑' : '新增'">
      <a-form :form="form" layout="horizontal" :label-col="{ span: 7 }" :wrapper-col="{ span: 14 }">
        <a-form-item label="类别" :required="true">
          <a-select @change="change" v-decorator="['type', { rules: [{ required: true, message: '请选择类别!' }] }]">
            <a-select-option value="1">资质信息</a-select-option>
            <a-select-option value="2">质量体系认证信息</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="资质名称" :required="true">
          <a-tree-select
            v-decorator="['qualName', { rules: [{ required: true, message: '请选择资质名称!' }] }]"
            show-search
            style="width: 100%"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            placeholder="请选择资质名称"
            allow-clear
            tree-default-expand-all
            :tree-data="treeData['A06']"
          ></a-tree-select>
        </a-form-item>
        <a-form-item label="资质等级" :required="true">
          <a-select
            v-decorator="['qualLevel', { rules: [{ required: true, message: '请选择资质等级!' }] }]"
            placeholder="请选择资质等级"
            style="width: 180px;"
            :options="qualCert_level['qualCert_level']"
          >
          </a-select></a-form-item
        ><a-form-item label="资质证书生效日期" :required="true">
          <a-date-picker
            v-decorator="['qualCertStartDate', { rules: [{ required: true, message: '请选择资质证书生效日期!' }] }]"
            format="YYYY-MM-DD"
          />
        </a-form-item>
        <a-form-item label="资质证书失效日期" :required="true">
          <a-date-picker
            v-decorator="['qualCertEndDate', { rules: [{ required: true, message: '请选择资质证书失效日期!' }] }]"
            format="YYYY-MM-DD"
            ><template slot="renderExtraFooter">
              <a-button type="link" @click="form.setFieldsValue({ qualCertEndDate: moment('9999-12-31') })"
                >长期</a-button
              >
            </template></a-date-picker
          >
        </a-form-item>
        <a-form-item label="资质证书编号" :required="true">
          <a-input v-decorator="['qualCertNo', { rules: [{ required: true, message: '请输入资质证书编号!' }] }]" />
        </a-form-item>
        <a-form-item label="发证单位" :required="true">
          <a-input v-decorator="['qualUnit', { rules: [{ required: true, message: '请输入发证单位!' }] }]" />
        </a-form-item>
        <a-form-item label="资质图片" :required="true">
          <j-upload v-decorator="['qualPath', { rules: [{ required: true, message: '请上传附件' }] }]"></j-upload>
        </a-form-item>
        <a-form-item label="备注" :required="false">
          <a-textarea v-decorator="['remark', { rules: [{ required: false, message: '请输入备注!' }] }]" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
export function getTitleById(treeData, id) {
  // 遍历树形数据结构
  function searchNode(node) {
    if (node.key === id) {
      return node.title
    }
    if (node.children) {
      for (let child of node.children) {
        let result = searchNode(child)
        if (result) {
          return result
        }
      }
    }
    return null
  }

  // 遍历树数据数组
  for (let item of treeData) {
    let result = searchNode(item)
    if (result) {
      return result
    }
  }

  return null // 如果没有找到，则返回 null
}
import moment from 'moment'
import { axios } from '@/utils/request'
import { mapGetters } from 'vuex'
import { assignKeyToValue } from '@views/user/register/reg_components/step2.vue'

export default {
  name: 'QualificationManager',
  components: {},
  props: {
    canFix: {
      type: Boolean,
    },
    // 基本类型检查 (`null` 和 `undefined` 会通过任何类型验证)
    legalCode: String,
  },
  data() {
    return {
      treeData: {},
      qualCert_level: {},
      imgBase: window._CONFIG['staticDomainURL'],
      form: this.$form.createForm(this),
      modalVisible: false,
      isEdit: false,
      currentRecord: {},
      data: [], // 这里应该是从后端获取的数据
      columns: [
        {
          title: '资质类别',
          dataIndex: 'type',
          key: 'type',
          customRender: (text, record, index) => {
            if (text == 1) {
              return '资质信息'
            }
            return '质量体系认证信息'
          },
        },
        {
          title: '资质名称',
          dataIndex: 'qualName',
          key: 'qualName',
          customRender: (text, record, index) => {
            return getTitleById(this.treeData['A06'], text) ?? text
          },
        },
        {
          title: '资质等级',
          dataIndex: 'qualLevel',
          key: 'qualLevel',
          customRender: (text, record, index) => {
            return this.qualCert_level['qualCert_level']?.find(v => v.value === text)?.label ?? text
          },
        },
        { title: '资质证书生效日期', dataIndex: 'qualCertStartDate', key: 'qualCertStartDate' },
        { title: '资质证书失效日期', dataIndex: 'qualCertEndDate', key: 'qualCertEndDate' },
        { title: '资质证书编号', dataIndex: 'qualCertNo', key: 'qualCertNo' },
        { title: '发证单位', dataIndex: 'qualUnit', key: 'qualUnit' },
        { title: '资质图片', dataIndex: 'qualPath', key: 'qualPath', scopedSlots: { customRender: 'qualPath' } },
        { title: '备注', dataIndex: 'remark', key: 'remark' },
        { title: '操作', scopedSlots: { customRender: 'action' }, key: 'action' },
      ],
      pagination: {
        current: 1,
        total: 1,
        pageSize: 2,
      },
    }
  },
  created() {
    this.getData()
    this.getTree({ async: false, pcode: 'A06' })
    this.getUserType('qualCert_level')
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  methods: {
    change(v){
      console.log(v)
      this.getTree({ async: false, pcode: v==1?'A06':'A09' })
      this.getUserType('qualCert_level',v)
    },
    handleTableChange(pagination, filters, sorter) {
      const pager = { ...this.pagination }
      pager.current = pagination.current
      this.pagination = pager
      console.log(pager)
      this.getData()
    },
    moment,
    getImgList(v) {
      if (v) return v.split(',')
      return [v]
    },
    getUserType(userType,v) {
      if(v==2){
        this.$set(this.qualCert_level, userType, [{label:'无等级',value:'1'}])
        return
      }
      this.$http.get('/register/common/getDictItems/' + userType).then(r => {
        this.$set(this.qualCert_level, userType, r.result)
      })
    },
    getTree(userType) {
      this.$http.get('/register/common/loadTreeRoot', { params: userType }).then(r => {
        assignKeyToValue(r.result)
        this.$set(this.treeData, 'A06', r.result)
      })
    },
    showAddForm() {
      this.modalVisible = true
      this.isEdit = false
      this.currentRecord = {}

      // 重置表单并设置默认值
      this.form.resetFields()
    },
    showEditForm(record) {
      this.modalVisible = true
      this.isEdit = true
      this.currentRecord = { ...record }
      this.$nextTick(() => {
        this.form.setFieldsValue({
          customDefinitionDataitem: record.customDefinitionDataitem,
          dataTimestamp: moment(record.dataTimestamp),
          id: record.id,
          legalCode: record.legalCode,
          platformCode: record.platformCode,
          qualCertEndDate: moment(record.qualCertEndDate),
          qualCertNo: record.qualCertNo,
          qualCertStartDate: moment(record.qualCertStartDate),
          qualLevel: record.qualLevel,
          qualName: record.qualName,
          qualPath: [record.qualPath], // 假设这里只有一个文件
          qualType: record.qualType,
          qualUnit: record.qualUnit,
          remark: record.remark,
          type: record.type,
        })
      })
    },

    hideForm() {
      this.modalVisible = false
    },
    handleOk(e) {
      e.preventDefault()

      this.form.validateFields((err, values) => {
        if (!err) {
          let obj = _.cloneDeep(values)
          Object.keys(obj).forEach(k => {
            if (Array.isArray(obj[k])) {
              obj[k] = obj[k].join()
            }
          })
          let url
          if (this.isEdit) {
            url = '/register/subjectLegalQual/edit'
          } else {
            url = '/register/subjectLegalQual/add'
          }
          obj.legalCode = this.legalCode
          obj.id = this.currentRecord.id
          axios.post(url, obj).then(v => {
            this.getData()
          })
          this.hideForm()
        }
      })
    },
    getData() {
      axios
        .get('/register/subjectLegalQual/list', {
          params: { legalCode: this.legalCode, pageSize: this.pagination.pageSize, pageNo: this.pagination.current },
        })
        .then(r => {
          this.data = r.result.records
          this.pagination.total = r.result.total
        })
    },
    handleCancel() {
      this.hideForm()
    },
    onDelete(record) {
      axios.delete('/register/subjectLegalQual/delete?id=' + record.id).then(r => {
        this.$message.success('删除成功')
        this.getData()
      })
    },
  },
}
</script>

<style scoped>
/* 可以在这里添加样式 */
</style>
